<template>
  <div class="orderdetail">
    <!-- 订单基本信息 -->
    <el-card class="detailcard">
        <template #header>
            <div class="cardheader">
                <span>订单基本信息</span>
                <el-tag :type="getOrderStatusType(orderInfo.status)">
                    {{getOrderStatusText(orderInfo.status)}}
                </el-tag>
            </div>
        </template>
        <el-descriptions :column="2" border>
            <el-descriptions-item label="订单编号">{{orderInfo.orderNo}}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{orderInfo.createTime}}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{orderInfo.payMethod === 1 ? '微信支付' : '支付宝'}}</el-descriptions-item>
            <el-descriptions-item label="支付时间">{{orderInfo.payTime || '-'}}</el-descriptions-item>
            <el-descriptions-item label="订单金额">{{orderInfo.totalAmount?.toFixed(2)}}</el-descriptions-item>
            <el-descriptions-item label="订单备注">{{orderInfo.remark || '-'}}</el-descriptions-item>
        </el-descriptions>
    </el-card>

    <!-- 收货信息 -->
    <el-card class="detailcard">
        <template #header>
            <div class="cardheader">
                <span>收货信息</span>
            </div>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="收货人">{{orderInfo.linkUser}}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{orderInfo.linkPhone}}</el-descriptions-item>
                <el-descriptions-item label="收货地址" :span="2">{{orderInfo.linkAddress}}</el-descriptions-item>
                <el-descriptions-item label="物流公司" v-if="orderInfo.status >= 2">{{getLogisticsCompany(orderInfo.logisticsCompany)}}</el-descriptions-item>
                <el-descriptions-item label="物流单号" v-if="orderInfo.status >= 2">{{orderInfo.trackingNo}}</el-descriptions-item>
            </el-descriptions>
        </template>
    </el-card>

    <!-- 商品信息 -->
    <el-card class="detailcard">
        <template #header>
            <div class="cardheader">
                <span>商品信息</span>
            </div>
        </template>
        <el-table :data="orderInfo.items" border style="width:100%">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column label="商品图片" width="100">
                <template #default="{row}">
                    <el-image 
                    :src="row.goodsImage"
                    :preview-src-list="[row.goodsImage]"
                    fit="cover"
                    style="width:50px;height:L50px" />
                </template>
            </el-table-column>
            <el-table-column prop="goodsNmae" label="商品名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="price" label="单价" width="120">
                <template #default="{row}">
                    ￥{{row.price.toFixed(2)}}
                </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" align="center" />
            <el-table-column label="小计" width="120">
                <template #default="{row}">
                    ￥{{(row.price * row.quantity).toFixed(2)}}
                </template>
            </el-table-column>
        </el-table>
        <div class="ordertotal">
            <span>订单总价：</span>
            <span class="price">￥{{orderInfo.totalPrice}}</span>
        </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operationbuttons">
        <el-button @click="goBack">返回列表</el-button>
        <el-button 
        v-if="orderInfo.status === 1"
        type="primary"
        @click="handleShip">发货</el-button>
    </div>

    <!-- 发货对话框 -->
    <el-dialog 
    v-model="shipDialogVisible"
    title="订单发货"
    width="500px">
    <el-form
    ref="shipFormRef"
    :model="shipForm"
    :rules="shipRules"
    label-width="100px">
    <el-form-item label="物流公司" prop="company">
        <el-select v-model="shipForm.company" placeholder="请选择物流公司">
            <el-option label="顺丰快递" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通快递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
        </el-select>
    </el-form-item>
    <el-form-item label="物流单号" prop="trackingNo">
        <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
    </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialogfooter">
            <el-button @click="shipDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmShip" :loading="shipLoading">确认</el-button>
        </span>
    </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import request from '@/utils/request'
import { ElMessage } from "element-plus";

const route = useRoute()
const router = useRouter()
const orderId = route.params.id
const orderInfo = ref({})
const shipDialogVisible = ref(false)
const shipLoading = ref(false)
const shipFormRef = ref(null)

const shipForm = reactive({
    company:'',
    trackingNo:''
})
const shipRules = {
    company:[
        {required:true,message:'请选择物流公司',trigger:'change'}
    ],
    trackingNo:[
        {required:true,message:'请输入物流单号',trigger:'blur'}
    ]
}

// 获取订单详情
const getOrderDetail = async () =>{
    try{
        const res = await request({
            url:`/order/${orderId}`,
            method:'get'
        })
        orderInfo.value=res.data
    }catch(error){
        console.error('获取订单详情失败：',error)
    }
}

//获取订单状态类型
const getOrderStatusType = (status) => {
  const types = {
    0: 'warning',   // 待付款
    1: 'primary',   // 待发货
    2: 'success',   // 已发货
    3: 'success',   // 已完成
    4: 'info'       // 已取消
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const texts = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return texts[status] || '未知'
}

// 获取物流公司名称
const getLogisticsCompany = (code) => {
  const companies = {
    'SF': '顺丰快递',
    'ZTO': '中通快递',
    'YTO': '圆通快递',
    'YD': '韵达快递'
  }
  return companies[code] || code
}

//返回列表
const goBack =()=>{
    router.push('')
}

//发货
const handleShip = ()=>{
    shipForm.company=''
    shipForm.trackingNo=''
    shipDialogVisible.value= true
}

//确认发货
const confirmShip =()=>{
    shipFormRef.value.validate(async(valid)=>{
        if(valid){
            shipLoading.value=true
            try{
                await request({
                    url:``,
                    method:'',
                    data:shipForm
                })
                ElMessage.success('发货成功')
                shipDialogVisible.value=false
                getOrderDetail()
            }catch(error){
                console.error('发货失败：',error)
            }finally{
                shipLoading.value=false
            }
        }
    })
}

onMounted(()=>{
    getOrderDetail()
})
</script>

<style scoped>
.detailcard{
    margin-bottom: 20px;
}
.cardheader{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.ordertotal{
    margin-top: 20px;
    text-align: right;
    padding-right: 20px;
}
.price{
    color: #f56c6c;
    font-size: 18px;
    font-weight: bold;
    margin-left: 10px;
}
.operationbuttons{
    display: flex;
    justify-content: center;
    margin-top: 20px;
    gap: 20px;
}
</style>